package com.example.Controller;

import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;


@RestController
@RequestMapping("/ai")
public class TTSController implements ApplicationRunner {

    @Resource
    private SpeechSynthesisModel speechSynthesisModel;

    private static final String FILE_PATH = "outputs/";

    // 保留原有代码，这里是文件保存路径的代码
    @PostMapping("/tts")
    @Cacheable(value = "aiCache", key = "#input")
    public String tts(String input, HttpServletResponse response) throws IOException {
        // 调用阿里云的语音合成服务
        SpeechSynthesisResponse responseData = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(input)
        );

        // 获取音频数据
        ByteBuffer byteBuffer = responseData.getResult().getOutput().getAudio();

        // 保存音频到文件系统
        File file = new File(FILE_PATH + "output.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteBuffer.array());
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        }

        return "/output.mp3";
    }

    // 在应用启动时创建输出目录
    @Override
    public void run(ApplicationArguments args) throws Exception {
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
